package com.sec.android.app.myfiles.module.local.securelocal;

import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.FolderSelectorBottomSheetActivity;
import com.sec.android.app.myfiles.feature.detailinfo.DetailsInfoMgr;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsFileListAdapterImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.provider.DbTableInfo.COLUMN_ID;
import com.sec.android.app.myfiles.provider.PrivateMyFilesProvider;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.SemFwWrapper;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.widget.listview.AbsListViewImp;
import com.sec.android.app.myfiles.widget.listview.FileListViewHolder;
import com.sec.android.app.myfiles.widget.listview.ListViewHolder;

import java.io.File;

public class SecureLocalFileListAdapterImp extends AbsFileListAdapterImp {

    private static String mSelection = null;
    private static String mSelectionHidden = null;

    int mIdIndex;
    int mMediaIdIndex;
    int mPathIndex;
    int mNameIndex;
    int mSizeIndex;
    int mDateIndex;
    int mTypeIndex;
    int mHiddenIndex;
    int mCntIndex;
    int mCntHiddenIndex;
    int mIsGear360ContentsIndex;
    SparseBooleanArray mBindedViews = new SparseBooleanArray();

    public SecureLocalFileListAdapterImp(Context context, NavigationInfo navigationInfo, AbsListViewImp listView, Cursor c, int flags) {
        super(context, navigationInfo, listView, c, flags);
        initDBIndex();

    }

    protected SecureLocalFileListAdapterImp(Context context, NavigationInfo navigationInfo, int layout, Cursor c, int flags) {
        super(context, navigationInfo, layout, c, flags);
        initDBIndex();
    }

    @Override
    public void changeCursor(Cursor cursor) {
        mBindedViews.clear();
        super.changeCursor(cursor);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mNavigationInfo != null && mNavigationInfo.getCurFragment() != null && FolderSelectorBottomSheetActivity.mBottomSheetDragMap.get(mNavigationInfo.getCurFragment().getProcessId())) {
            if (mBindedViews.get(position)) {
                if (convertView == null) {
                    convertView = super.getView(position, convertView, parent);
                }
                if (position == 0 && convertView != null && convertView.getTag() != null && !((ListViewHolder) convertView.getTag()).getView(FileListViewHolder.NAME, TextView.class).getText().equals(mContext.getResources().getString(R.string.create_folder))) {
                    convertView = super.getView(position, convertView, parent);
                }
                return convertView;
            } else {
                mBindedViews.put(position, true);
            }
        }
        return super.getView(position, convertView, parent);
    }

    @Override
    protected void _bindView(Context context, ListViewHolder vh, View v, FileRecord record, int position) {
        super._bindView(context, vh, v, record, position);
        if (record.getPath() == null && record.getName().equals(context.getResources().getString(R.string.create_folder))) {
            _bindCreateFolderView(vh, v);
        }
        DetailsInfoMgr.getInstance().loadChildCount(context, record, vh.getView(FileListViewHolder.SIZE, TextView.class));
    }

    private void initDBIndex() {
        mIdIndex = mTableInfo.getIndex(COLUMN_ID.ID);
        mMediaIdIndex = mTableInfo.getIndex(COLUMN_ID.MEDIA_ID);
        mPathIndex = mTableInfo.getIndex(COLUMN_ID.PATH);
        mNameIndex = mTableInfo.getIndex(COLUMN_ID.NAME);
        mSizeIndex = mTableInfo.getIndex(COLUMN_ID.SIZE);
        mDateIndex = mTableInfo.getIndex(COLUMN_ID.DATE);
        mTypeIndex = mTableInfo.getIndex(COLUMN_ID.FILE_TYPE);
        mHiddenIndex = mTableInfo.getIndex(COLUMN_ID.IS_HIDDEN);
        mCntIndex = mTableInfo.getIndex(COLUMN_ID.ITEM_COUNT);
        mCntHiddenIndex = mTableInfo.getIndex(COLUMN_ID.ITEM_COUNT_HIDDEN);
        mIsGear360ContentsIndex = mTableInfo.getIndex(COLUMN_ID.IS_360_CONTENTS);
    }

    @Override
    public String getSelection() {
        boolean showHidden = PreferenceUtils.getShowHiddenFiles(mContext);
        String strRet;
        if (showHidden) {
            strRet = _getSelectionShowHidden();
        } else {
            strRet = _getSelection();
        }
        return strRet;
    }

    private String _getSelection() {
        if (mSelection == null) {
            mSelection = _getSelectionShowHidden() + " AND " + mTableInfo.getColumnName(COLUMN_ID.IS_HIDDEN) + "=0";
        }
        return mSelection;
    }

    private String _getSelectionShowHidden() {
        if (mSelectionHidden == null) {
            mSelectionHidden = mTableInfo.getColumnName(COLUMN_ID.PATH) + "=?";
        }
        return mSelectionHidden;
    }

    @Override
    public String[] getSelectionArgs() {
        return new String[]{mCurRecord.getFullPath()};
    }

    @Override
    protected FileRecord _getFileRecord(Cursor cursor) {
        FileRecord ret = null;

        if (cursor != null) {
            try {
                int mediaId = cursor.getInt(mMediaIdIndex);
                String path = cursor.getString(mPathIndex);
                String name = cursor.getString(mNameIndex);
                long size = cursor.getLong(mSizeIndex);
                long date = cursor.getLong(mDateIndex);
                int fileType = cursor.getInt(mTypeIndex);
                int isHidden = cursor.getInt(mHiddenIndex);
                int itemCount = cursor.getInt(mCntIndex);
                int itemCountHidden = cursor.getInt(mCntHiddenIndex);
                int isGear360Contents = cursor.getInt(mIsGear360ContentsIndex);


                ret = FileRecord.createFileRecord(getStorageType(), mediaId, path, name, size, date, fileType, isHidden, itemCount, itemCountHidden);
                if (ret != null) {
                    ret.setGear360Contents(isGear360Contents == 1);
                    updateDirInfo(ret);
                }
            } catch (CursorIndexOutOfBoundsException e) {
                Log.e(this, "CursorIndexOutOfBoundsException:" + e.toString());
            }
        }
        return ret;
    }

    private void updateDirInfo(FileRecord record) {
        if (record.isDirectory()) {
            File file = SemFwWrapper.file(record.getFullPath());
            if (file.exists() && file.lastModified() != record.getDate()) {
                Log.d(this, "folder is changed");
                FileRecord parent = record.getParent();
                if (parent != null) {
                    PrivateMyFilesProvider.clearCache(mContext, parent);
                }
                DetailsInfoMgr.getInstance().clearChildCountCache(record);
            }
        }
    }


    @Override
    public String getFilePath(Cursor cursor) {
        return getFilePath(cursor, mTableInfo.getIndex(COLUMN_ID.PATH), mTableInfo.getIndex(COLUMN_ID.NAME));
    }

    @Override
    public StorageType getStorageType() {
        return StorageType.Local;
    }

    @Override
    public boolean _isEnabled(int position) {
        boolean bRet = isCheckable(position);
        FileRecord record = getFileRecord(position);
        if (mNavigationInfo != null && mNavigationInfo.isPickerMode()) {
            if (record != null && record.isDirectory()) {
                bRet = true;
            }
        }
        return bRet;
    }

    @Override
    public Object[] getCreateFolderItem() {
        return new Object[]{
                0,      //ID
                -1,     //MediaId
                null,   //path
                mContext.getResources().getString(R.string.create_folder),  //name
                0,      //size
                0,      //date
                0,      //type
                null,   //ext
                0,      //isDir
                0,      //isHidden
                0,      //item_cnt
                0,      //  item_cnt_hidden
                0,       // is 360
                null,//width,
                null,//height
                null,//duration
                null,//artist
                null//album
        };
    }

    @Override
    public int getEmptyTextId() {
        int id = super.getEmptyTextId();
        if (StorageMonitor.isRemovedExtSDCard(mCurRecord.getFullPath())) {
            id = R.string.no_sd_card;
        }

        return id;
    }

    @Override
    public int getEmptySubTextId() {
        int id = super.getEmptySubTextId();
        if (StorageMonitor.isRemovedExtSDCard(mCurRecord.getFullPath())) {
            id = AppFeatures.isTablet() ? R.string.no_sdcard_files_tablet : R.string.no_sdcard_files_phone;
        }

        return id;
    }

    @Override
    public int getEmptyIconId() {
        int id = super.getEmptyIconId();
        if (StorageMonitor.isRemovedExtSDCard(mCurRecord.getFullPath())) {
            id = R.raw.myfile_sdcard;
        }
        return id;
    }
}
